package com.rockcent.wechat.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.mall.lib.domain.CustomerShare;
import com.rockcent.mall.lib.domain.enumclass.CustomerShareStatus;
import com.rockcent.mall.lib.dto.CustomerDto;
import com.rockcent.mall.lib.dto.CustomerShareDto;
import com.rockcent.mall.lib.dto.MerchantOrderItemDto;
import com.rockcent.mall.lib.repository.CustomerShareRepository;
import com.rockcent.wechat.Routes;
import com.rockcent.wechat.helper.CustomerHelper;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * 用户分享
 * Created by marco on 2017/6/21.
 */
@RestController
@RequestMapping(value = Routes.API_PREFIX)
public class CustomerShareController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(CustomerShareController.class);

    @Autowired
    private CustomerHelper customerHelper;
    @Autowired
    private CustomerShareRepository customerShareRepository;

    /**
     * @api {post} /api/v2/customer/shared/product/save 用户分享
     * @apiGroup customer
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} domain <code>必须参数</code>对应平台C端域名
     * @apiHeader {String} userToken <code>必须参数</code>用户Token
     *
     * @apiParam {String} productType 产品类型，GOODS("商品"), SERVICE("服务")
     * @apiParam {Long} productId 产品Id
     * @apiParam {String} productImageUrl 产品图片链接
     * @apiParam {String} userImageUrl 用户图片链接
     * @apiParam {String} userName 用户名称
     * @apiParam {Long} originalPrice 原价
     * @apiParam {Long} friendPrice 友价
     * @apiParam {String} shareTitle 分享标题 <code>必须参数</code>
     * @apiParam {String} shareContent 分享内容 <code>必须参数</code>
     * @apiParam {String} shareCode 分享码
     *
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} id 分享ID
     * @apiSuccess {Long} customerId 用户ID
     * @apiSuccess {String} productType 产品类型，GOODS("商品"), SERVICE("服务")
     * @apiSuccess {Long} productId 产品Id
     * @apiSuccess {String} productImageUrl 产品图片链接
     * @apiSuccess {String} userImageUrl 用户图片链接
     * @apiSuccess {String} userName 用户名称
     * @apiSuccess {Long} originalPrice 原价
     * @apiSuccess {Long} friendPrice 友价
     * @apiSuccess {String} shareTitle 分享标题
     * @apiSuccess {String} shareContent 分享内容
     * @apiSuccess {String} status 状态，SUCCESS("成功"), WAITING("等待中")
     * @apiSuccess {String} shareCode 分享码
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "id": 1,
     *     "version": 0,
     *     "mallId": 51,
     *     "customerId": 35,
     *     "userImageUrl": "http://www.uat.rockcent.com",
     *     "userName": "test",
     *     "productId": 1111,
     *     "productImageUrl": "http://www.uat.rockcent.com",
     *     "productType": "GOODS",
     *     "originalPrice": 200,
     *     "friendPrice": 100,
     *     "shareTitle": "test1234",
     *     "shareContent": "test12456",
     *     "status": "WAITING"
     *   }
     * }
     */
    @RequestMapping(value = Routes.CUSTOMER_SHARED_PRODUCT_SAVE, method = RequestMethod.POST)
    public JsonResult save(@RequestBody CustomerShareDto dto, HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            Long customerId =  customerDto.getId();
            Long mallId = customerDto.getMallId();
            Long productId = dto.getProductId();
            String productImageUrl = dto.getProductImageUrl();
            String productType = dto.getProductType();
            BigDecimal friendPrice = dto.getFriendPrice();
            BigDecimal originalPrice = dto.getOriginalPrice();
            String userName = dto.getUserName();
            String userImageUrl = dto.getUserImageUrl();
            String title = dto.getShareTitle();
            if(StringUtils.isEmpty(title)) {
                jr.remind("分享标题不能为空", log);
                return;
            }
            String content = dto.getShareContent();
            if(StringUtils.isEmpty(content)) {
                jr.remind("分享内容不能为空", log);
                return;
            }
            String shareCode = dto.getShareCode();
            CustomerShare customerShare = new CustomerShare();
            customerShare.setMallId(mallId);
            customerShare.setCustomerId(customerId);
            customerShare.setStatus(CustomerShareStatus.WAITING);
            customerShare.setFriendPrice(friendPrice);
            customerShare.setOriginalPrice(originalPrice);
            customerShare.setProductId(productId);
            customerShare.setProductImageUrl(productImageUrl);
            customerShare.setProductType(productType);
            customerShare.setUserImageUrl(userImageUrl);
            customerShare.setUserName(userName);
            customerShare.setShareTitle(title);
            customerShare.setShareContent(content);
            customerShare.setShareCode(shareCode);
            jr.data = customerShareRepository.save(customerShare);
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /api/v2/customer/shared/product/update 用户分享更新状态
     * @apiGroup customer
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} domain <code>必须参数</code>对应平台C端域名
     * @apiHeader {String} userToken <code>必须参数</code>用户Token
     *
     * @apiParam {Long} id 分享Id
     * @apiParam {String} status 状态，SUCCESS("成功"), WAITING("等待中")
     * @apiParam {String} shareContent 分享内容
     *
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} id 分享ID
     * @apiSuccess {Long} customerId 用户ID
     * @apiSuccess {String} productType 产品类型，GOODS("商品"), SERVICE("服务")
     * @apiSuccess {Long} productId 产品Id
     * @apiSuccess {String} productImageUrl 产品图片链接
     * @apiSuccess {String} userImageUrl 用户图片链接
     * @apiSuccess {String} userName 用户名称
     * @apiSuccess {Long} originalPrice 原价
     * @apiSuccess {Long} friendPrice 友价
     * @apiSuccess {String} shareTitle 分享标题
     * @apiSuccess {String} shareContent 分享内容
     * @apiSuccess {String} status 状态，SUCCESS("成功"), WAITING("等待中")
     * @apiSuccess {String} shareCode 分享码
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "id": 1,
     *     "dateCreated": "2017-06-21 17:00:51",
     *     "lastUpdated": "2017-06-21 17:00:51",
     *     "version": 0,
     *     "mallId": 51,
     *     "customerId": 35,
     *     "userImageUrl": "http://www.uat.rockcent.com",
     *     "userName": "test",
     *     "productId": 1111,
     *     "productImageUrl": "http://www.uat.rockcent.com",
     *     "productType": "GOODS",
     *     "originalPrice": 200,
     *     "friendPrice": 100,
     *     "shareTitle": "test1234",
     *     "shareContent": "test12456",
     *     "status": "SUCCESS"
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.CUSTOMER_SHARED_PRODUCT_UPDATE, method = RequestMethod.POST)
    public JsonResult update(@RequestBody CustomerShareDto dto, HttpServletRequest request) {
        RestDoing doing = jr -> {
            Long id = dto.getId();
            if(id==null) {
                jr.remind("Id 不能为空",log);
                return;
            }
            String status = dto.getStatus();
            if(StringUtils.isEmpty(status)) {
                jr.remind("状态代码不能为空", log);
                return;
            }
            if(!EnumUtils.isValidEnum(CustomerShareStatus.class, status)) {
                jr.remind("状态代码不正确", log);
                return;
            }
            CustomerShare customerShare = customerShareRepository.findOne(id);
            if(customerShare==null) {
                jr.remind("Id 记录不存在",log);
                return;
            }
            if(StringUtils.isNotEmpty(dto.getShareContent())) {
                customerShare.setShareContent(dto.getShareContent());
            }
            customerShare.setStatus(CustomerShareStatus.valueOf(status));
            jr.data = customerShareRepository.save(customerShare);
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /api/v2/customer/shared/product/info 用户分享详情
     * @apiGroup customer
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} domain <code>必须参数</code>对应平台C端域名
     * @apiHeader {String} userToken <code>必须参数</code>用户Token
     *
     * @apiParam {Long} id 分享Id
     *
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} id 分享ID
     * @apiSuccess {Long} customerId 用户ID
     * @apiSuccess {String} productType 产品类型，GOODS("商品"), GIFTBAG("礼包")
     * @apiSuccess {Long} productId 产品Id
     * @apiSuccess {String} productImageUrl 产品图片链接
     * @apiSuccess {String} userImageUrl 用户图片链接
     * @apiSuccess {String} userName 用户名称
     * @apiSuccess {Long} originalPrice 原价
     * @apiSuccess {Long} friendPrice 友价
     * @apiSuccess {String} shareTitle 分享标题
     * @apiSuccess {String} shareContent 分享内容
     * @apiSuccess {String} status 状态，SUCCESS("成功"), WAITING("等待中")
     * @apiSuccess {String} shareCode 分享码
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "id": 1,
     *     "dateCreated": "2017-06-21 17:00:51",
     *     "lastUpdated": "2017-06-21 17:00:51",
     *     "version": 0,
     *     "mallId": 51,
     *     "customerId": 35,
     *     "userImageUrl": "http://www.uat.rockcent.com",
     *     "userName": "test",
     *     "productId": 1111,
     *     "productImageUrl": "http://www.uat.rockcent.com",
     *     "productType": "GOODS",
     *     "originalPrice": 200,
     *     "friendPrice": 100,
     *     "shareTitle": "test1234",
     *     "shareContent": "test12456",
     *     "status": "WAITING"
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.CUSTOMER_SHARED_PRODUCT_INFO, method = RequestMethod.GET)
    public JsonResult info(CustomerShareDto dto, HttpServletRequest request) {
        RestDoing doing = jr -> {
            Long id = dto.getId();
            if(id==null) {
                jr.remind("Id 不能为空",log);
                return;
            }
            CustomerShare customerShare = customerShareRepository.findOne(id);
            if(customerShare==null) {
                jr.remind("Id 记录不存在",log);
                return;
            }
            jr.data = customerShare;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /api/v2/customer/shared/product/orders 用户分享产品产生的订单
     * @apiGroup customer
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} domain <code>必须参数</code>对应平台C端域名
     * @apiHeader {String} userToken <code>必须参数</code>用户Token
     *
     * @apiParam {Long} productId <code>必须参数</code>产品Id
     *
     * @apiSuccess {BigDecimal} baseAmount 售价
     * @apiSuccess {String} settleStatus 状态
     * @apiSuccess {String} sharerNickName 好友名称
     * @apiSuccess {BigDecimal} shareFee 分享返利
     * @apiSuccess {String} productName 产品名称
     * @apiSuccess {String} dateSettled 结算时间
     * @apiSuccess {String} dateCreated 下单时间
     * @apiSuccess {String} logoUrl 图片地址
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "data": [
     *       {
     *         "dateCreated": "2017-01-12 17:39:58",
     *         "dateSettled": "2017-01-12 17:39:00",
     *         "productName": "商品+物流2哇",
     *         "shareFee": 4.4,
     *         "sharerNickName": "胖墩",
     *         "settleStatus": "SETTLED",
     *         "baseAmount": 77
     *       }
     *     ],
     *     "totalCount": 1,
     *     "totalPage": 1,
     *     "pageNo": 0,
     *     "pageSize": 10
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.CUSTOMER_SHARED_PRODUCT_ORDERS, method = RequestMethod.GET)
    public JsonResult shareProductOrders(CustomerShareDto dto, HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Long productId = dto.getProductId();
            if(productId==null) {
                jsonResult.remind("产品Id 不能为空",log);
                return;
            }
            PageResult<MerchantOrderItemDto> orderItemDtoList = customerShareRepository.findMerchaOrderItemByShareIdAndProductId(this.getPage(dto.getPageNo(), dto.getPageSize()),customerDto.getId(),productId);
            jsonResult.data=orderItemDtoList;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /api/v2/customer/shared/giftpacket/orders 用户分享礼包产生的订单
     * @apiGroup customer
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} domain <code>必须参数</code>对应平台C端域名
     * @apiHeader {String} userToken <code>必须参数</code>用户Token
     *
     * @apiParam {Long} giftPacketId <code>必须参数</code>礼包Id
     *
     * @apiSuccess {BigDecimal} baseAmount 售价
     * @apiSuccess {String} settleStatus 状态
     * @apiSuccess {String} sharerNickName 好友名称
     * @apiSuccess {BigDecimal} shareFee 分享返利
     * @apiSuccess {String} giftName 礼包名称
     * @apiSuccess {String} dateSettled 结算时间
     * @apiSuccess {String} dateCreated 下单时间
     * @apiSuccess {String} logoUrl 礼包地址
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "data": [
     *       {
     *         "dateCreated": "2017-01-12 17:39:58",
     *         "dateSettled": "2017-01-12 17:39:00",
     *         "giftName": "礼包2哇",
     *         "shareFee": 4.4,
     *         "sharerNickName": "胖墩",
     *         "settleStatus": "FINISHED",
     *         "baseAmount": 77
     *       }
     *     ],
     *     "totalCount": 1,
     *     "totalPage": 1,
     *     "pageNo": 0,
     *     "pageSize": 10
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.CUSTOMER_SHARED_GIFTPACKET_ORDERS, method = RequestMethod.GET)
    public JsonResult shareGiftPacketOrders(CustomerShareDto dto, HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Long giftPacketId = dto.getGiftPacketId();
            if(giftPacketId==null) {
                jsonResult.remind("礼包Id 不能为空",log);
                return;
            }
            PageResult<MerchantOrderItemDto> orderItemDtoList = customerShareRepository.findMallOrderByShareIdAndGiftPacketId(this.getPage(dto.getPageNo(), dto.getPageSize()),customerDto.getId(),giftPacketId);
            jsonResult.data=orderItemDtoList;
        };
        return doing.go(request, log);
    }
}
